package com.maegul.web.components;

import java.text.NumberFormat;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import com.maegul.data.entities.CartItem;
import com.maegul.web.MaegulSession;
import com.maegul.web.models.POJO.Cart;

public class CheckOutCart extends Panel {

	private static final long serialVersionUID = 1L;

	private Cart cart;

	public CheckOutCart(String id, Cart cart) {
		super(id);

		this.cart = cart;

		add(new ListView<CartItem>("items", new PropertyModel<List<CartItem>>(
				this, "cart.items")) {

			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(ListItem<CartItem> item) {
				CartItem ci = item.getModelObject();
				item.add(new Label("name", ci.getMediaItem().getName()));
				item.add(new Label("price", "$" + ci.getMediaItem().getPrice()));
				item.add(new AjaxFallbackLink<CartItem>("remove", item.getModel()) {

					private static final long serialVersionUID = 1L;

					@Override
					public void onClick(AjaxRequestTarget target) {
						CartItem cItem = getModelObject();
						getCart().getItems().remove(cItem);
						
					}
				});
			}

		});

		add(new Label("total", new Model<String>() {

			private static final long serialVersionUID = 1L;

			@Override
			public String getObject() {
				double total = 0;
				NumberFormat nf = NumberFormat.getCurrencyInstance();

				List<CartItem> cart = MaegulSession.get().getCart();
				for (CartItem item : cart) {
					total += item.getMediaItem().getPrice();
				}

				return nf.format(total);
			}
		}));
	}
	
	private Cart getCart(){
		return cart;
	}

}
